package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.User;
import com.example.forum.services.IUserService;
import com.example.forum.utils.MD5Util;
import com.example.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @Author: wenjingyuan
 * @Date: 2023/09/21/17:10
 * @Description:
 */
//对usercontroller的API接口的描述
@Api(tags = "用户接口")
//这是一个返回数据的controller
@RestController
//路由映射
@RequestMapping("/user")
//日志
@Slf4j
public class UserController {
    @Resource
    private IUserService userService;

    @ApiOperation("用户注册")
    @PostMapping ("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //首先我们在上述注解中已经对于用户传过来的参数进行校验
        //接下来我们对于两次密码进行校验
        if(!password.equals(passwordRepeat)){
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //准备数据
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt= UUIDUtil.UUID_32();
        String encryPassword= MD5Util.md5salt(password,salt);
        user.setPassword(encryPassword);
        user.setSalt(salt);
        //调用service方法
        userService.createNormalUse(user);
        return AppResult.success();
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //1.调用userservice的login的方法，返回user对象
        User user = userService.login(username, password);
        if(user==null){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //2.将user对象加入到session的作用域中
        //true表示没有session就创建一个session
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //3.返回结果
        return AppResult.success();
    }

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    //required = false标注参数可以为空
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        User user=null;
        if(id == null){
            //1.如果我们的id没有参数，那么就从session里获取用户信息
            //false代表如果没有不创建session
            HttpSession session = request.getSession(false);
            user= (User) session.getAttribute(AppConfig.USER_SESSION);
        }else{
            //2.如果有id 就从数据库中查询
            user= userService.selectById(id);
        }
        //判断用户是否为空
        if(user==null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //返回正常的结果
        return  AppResult.success(user);
    }

    /**
     * 用户退出登录
     * @param request
     * @return
     */
    @ApiOperation("用户退出")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //拿到session
        HttpSession session = request.getSession(false);
        //判断session是否有效
        if(session!=null){
            //此时用户已经登录,销毁session
            //打印日志
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }

    /**
     * 修改个人信息
     * @param username
     * @param nickname
     * @param gender
     * @param email
     * @param remark
     * @param phonenumber
     * @return
     */
    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("登录名") @RequestParam(value = "username",required = false) String username,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false)  String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false)  Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false)  String email,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false)  String remark,
                                @ApiParam("电话号码") @RequestParam(value = "phonenumber",required = false)  String phonenumber){

        HttpSession session = request.getSession(false);
        User user1= (User) session.getAttribute(AppConfig.USER_SESSION);
        if(StringUtils.isEmpty(username) && StringUtils.isEmpty(nickname)
        && gender==null && StringUtils.isEmpty(email) &&
        StringUtils.isEmpty(phonenumber) && StringUtils.isEmpty(remark)){
           return AppResult.failed("请输入要修改的信息");
        }

        //构建user对象
        User user=new User();
        user.setId(user1.getId());
        user.setUsername(username);
        user.setGender(gender);
        user.setNickname(nickname);
        user.setEmail(email);
        user.setPhonenumber(phonenumber);
        user.setRemark(remark);

        //调用service
        userService.modifyInfo(user);
        //查询最新的用户信息
        User user2 = userService.selectById(user.getId());
        //将最新的用户信息设置给session
        session.setAttribute(AppConfig.USER_SESSION,user2);
        return AppResult.success(user2);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult  modifyPassword(HttpServletRequest request,
                                     @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                     @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                     @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //校验两次输入的密码是否一致
        if(!newPassword.equals(passwordRepeat)){
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //从session拿到用户
        HttpSession session = request.getSession(false);
        User user= (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service
        userService.modifyPassword(user.getId(),newPassword,oldPassword);
        //返回结果
        return AppResult.success();
    }
}
